/**
 * @file 进度条管理组件
 * @date 2025/11/20 16:08:01
 * @author lyqjob@yeah.net
 * @description 负责在路由切换时显示进度条，并记录有效路径
 */

import { useEffect } from 'react';
import { useLocation } from 'react-router-dom';
import { useAuth } from '@/hooks/useAuth';
import NProgress from 'nprogress';
import 'nprogress/nprogress.css';

// 配置 NProgress
NProgress.configure({ 
  parent: '#root',
  easing: 'ease', 
  speed: 500,
  showSpinner: false, // 右侧loading图标
  minimum: 0.1,
  trickleSpeed: 200, // 递增速度
  trickle: true, // 自动递增
});


const ProgressManager = () => {
  const location = useLocation();
  const { currentUser, isLogin } = useAuth();

  useEffect(() => {
    if (currentUser?.name && isLogin) {
      // 将 NProgress 挂载到 window 对象上
      window.process = NProgress;
      
      const startTimer = setTimeout(() => {
        window.process.start();
        window.process.inc();
      }, 180);
      
      const doneTimer = setTimeout(() => {
        window.process.done();
      }, 600);

      // 记录有效路径（排除登录页和404页）
      if (location.pathname !== "/login" && location.pathname !== "*") {
        sessionStorage.setItem("lastValidPath", location.pathname);
      }

      return () => {
        clearTimeout(startTimer);
        clearTimeout(doneTimer);
        window.process.done();
      };
    }
  }, [location.pathname, currentUser?.name, isLogin]);

  // ProgressManager 是纯逻辑组件，不渲染任何 UI
  return null;
};

export default ProgressManager;